﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ProDivingAdmin2salmon14
{
    public static class FileManager
    {

        public static DiveDatabaseDataSet diveDataBase = new DiveDatabaseDataSet();
        public static Dictionary<string, Tuple<float, string>> diveList { get; set; }

        public static string GetDiveName(string diveCode) 
        {
            if (diveList.Keys.Contains(diveCode))
            {
                return diveList[diveCode].Item2;
            }
            else 
            {
                return "Dive not found!";
            }
        }

        public static DiverList LoadDivers(string filePath)
        { 
            DiverList returnDivers = new DiverList();

            string[] divers = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("ISO-8859-1"));
            foreach (var diver in divers) 
            {
                string[] tempDiver = diver.Trim().Split(':');

                string[] tempInfo = tempDiver[0].Split(',');
                string[] tempDives = tempDiver[1].Split(',');

                List<Dive> dives = new List<Dive>();
                foreach (var tempDive in tempDives)
                {
                    bool added = false;
                    string tempStr = tempDive.Trim();
                    while (!added)
                    {  
                        if (Contest.validDives.Keys.Contains(tempStr))
                        {
                            dives.Add(new Dive(tempStr));
                            added = true;
                        }
                        else
                        {
                            added = true;
                            //Popup där användaren får veta att hoppet är ogiltigt
                            //Möjlighet ges att skriva ett hopp som är giltigt.
                            //tempStr sätts till den nya inmatningen.
                        }   
                    }
                }
                returnDivers.Add(new Diver(tempInfo[0].Trim(), tempInfo[1].Trim(), Int32.Parse(tempInfo[2]), tempInfo[3].Trim(), dives));
            }
            //returnDivers.Shuffle();
            return returnDivers;
        }

        public static void LoadDives(string filePath)
        {
            diveList = new Dictionary<string, Tuple<float, string>>();
            string[] dives = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("ISO-8859-1"));
            foreach (var dive in dives) 
            {
                if (dive != "\n" && dive != "" && dive != " ")
                {
                    string[] temp = dive.Split(':');
                    diveList[temp[0]] = new Tuple<float, string>(float.Parse(temp[1], System.Globalization.CultureInfo.InvariantCulture), temp[2]);
                }
            } 
        }

        public static void LoadDives(string filePath, DataTable table)
        {
            DataRow row;
            string[] dives = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("ISO-8859-1"));

            foreach (var dive in dives)
            {
                if (dive != "\n" && dive != "" && dive != " ")
                {
                    string[] temp = dive.Split(':');
                    row = table.NewRow();

                    row["DiveCode"] = temp[0];
                    row["DiveName"] = temp[2];
                    row["DiveDiff"] = float.Parse(temp[1], System.Globalization.CultureInfo.InvariantCulture);

                    table.Rows.Add(row);
                }
            }
        }

        public static List<Judge> LoadJudges(string filePath)
        {
            Random rand = new Random();
            int id;
            int order = 0;
            bool changed = true;
            List<Judge> returnJudges = new List<Judge>();
            string[] judges = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("ISO-8859-1"));
            foreach (var judge in judges) 
            {
                changed = true;
                id = rand.Next(0, 100);
                while (changed)
                {
                    changed = false;
                    foreach (var returnJudge in returnJudges)
                    {
                        if (returnJudge.ID == id)
                        {
                            changed = true;
                            id = rand.Next(0, 100);
                        }
                    }
                }
                string[] temp = judge.Split(',');
                returnJudges.Add(new Judge(temp[0], temp[1], id, order));
                order++;
            }
            return returnJudges;
        }

        public static void SaveDivers(DiverList diverList, string filePath) 
        {
            string[] diversString = new string[diverList.Count];
            string diverString;
            int i = 0;

            foreach (var diver in diverList)
            {
                diverString = diver.fullName + ", " + diver.Nr + ", " + diver.ID + ", " + diver.nationality + ":" + diver.diveList[0].diveCode + "," + diver.diveList[1].diveCode + "," + diver.diveList[2].diveCode + "," + diver.diveList[3].diveCode + "," + diver.diveList[4].diveCode;
                diversString[i] = diverString;
                i++;
            }
            using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.GetEncoding("ISO-8859-1")))
            {
                foreach (string str in diversString)
                {
                    writer.WriteLine(str);
                }
            }
        }


        public static void SaveContest(string filePath, Contest contest)
        {
            contest.backupJudgeList.Clear();
            contest.BackupJudgeList();
            contest.BackupJudgeScores();

            foreach (var judge in contest.backupJudgeList)
            {
                judge.isConnected = false;
            }
            DateTime date = new DateTime();
            date.ToString("d");
            if (filePath == null)
            {
                filePath = "C:\\" + date;
            }


            try
            {
                XmlSerializer contestSerializer = new XmlSerializer(typeof(Contest));
                TextWriter textWriter = new StreamWriter(filePath);
                contestSerializer.Serialize(textWriter, contest);
                

                textWriter.Close();
            }
            catch (InvalidOperationException e)
            {
                System.Console.WriteLine(e.InnerException.Message);
            }

        }

        public static Contest LoadContest(string filePath)
        {
            //CommunicationServer._serverSocket.Disconnect(false);
            Contest.validDives.Clear();
            try
            {
                XmlSerializer contestDeserializer = new XmlSerializer(typeof(Contest));
                TextReader textReader = new StreamReader(filePath);

                //object contest = new Contest(true);

                object contest = contestDeserializer.Deserialize(textReader);
                textReader.Close();

                Contest temp = (Contest)contest;
                temp.GenerateValidDives();

                Contest.judgeList.Clear();

                foreach (var judge in temp.backupJudgeList)
                {
                    Contest.judgeList.Add(judge);
                }

                foreach (var score in temp.backupJudgeScores)
                {
                    Contest.judgeScores.Add(score);
                }


                return (Contest)contest;
            }
            catch (InvalidOperationException e)
            {
                System.Console.WriteLine(e.InnerException);
                return new Contest(true);
            }

            CommunicationServer.sendText = "";
        }

        public static void InitDiveDataBase()
        {
            DataTable diveTable = new DataTable("Dives");

            DataColumn diveID = new DataColumn();
            diveID.DataType = Type.GetType("System.Int32");
            diveID.ColumnName = "DiveID";
            diveID.AutoIncrement = true;
            diveTable.Columns.Add(diveID);

            DataColumn diveCode = new DataColumn();
            diveCode.DataType = Type.GetType("System.String");
            diveCode.ColumnName = "DiveCode";
            diveTable.Columns.Add(diveCode);

            DataColumn diveName = new DataColumn();
            diveName.DataType = Type.GetType("System.String");
            diveName.ColumnName = "DiveName";
            diveTable.Columns.Add(diveName);

            DataColumn diveDiff = new DataColumn();
            diveDiff.DataType = Type.GetType("System.Decimal");
            diveDiff.ColumnName = "DiveDiff";
            diveTable.Columns.Add(diveDiff);

            DataColumn[] keys = new DataColumn[1];
            keys[0] = diveID;
            diveTable.PrimaryKey = keys;

            diveDataBase = new DiveDatabaseDataSet();
            diveDataBase.Tables.Add(diveTable);

            LoadDives("DivingScores_and_Names2salmon14.txt", diveDataBase.Tables[0]);

            System.Console.WriteLine(diveDataBase.Tables[0].Rows.Count.ToString());

            diveDataBase.AcceptChanges();

            var root = diveDataBase.Tables.SyncRoot;

            diveDataBase.AcceptChanges();
        }
    }
}
